package com.cans.client;

import com.cans.handler.ClientHandler;
import com.cans.user.IUserService;
import com.cans.user.User;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

import javax.xml.namespace.QName;
import javax.xml.ws.handler.Handler;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: cans
 * @date: 2017/11/16
 * @description:
 */
public class ServiceClient {

    private static final String USER_NAME = "admin";
    private static final String PASS_WORD = "pass";

    public static void main(String[] args) throws Exception {
        serviceTest();

//        serviceTest1();

//        serviceTest2();
    }

    /**
     * 使用代码生成调用
     */
    public static void serviceTest(){
        try {
            // 接口地址
            String address = "http://localhost:8080/soap/user?wsdl";
            // 代理工厂
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
            // 添加验证头信息
            List<Handler> handlerList = new ArrayList<>();
            handlerList.add(new ClientHandler(USER_NAME, PASS_WORD));
            jaxWsProxyFactoryBean.setHandlers(handlerList);
            // 设置代理地址
            jaxWsProxyFactoryBean.setAddress(address);
            // 设置接口类型
            jaxWsProxyFactoryBean.setServiceClass(IUserService.class);
            // 创建一个代理接口实现
            IUserService cs = (IUserService) jaxWsProxyFactoryBean.create();

            // 调用代理接口的方法调用并返回结果
            User user = cs.getUser(10002L);
            System.out.println("返回结果:" + user.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 动态调用
     * @throws Exception
     */
    public static void serviceTest1() throws Exception {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient("http://localhost:8080/soap/user?wsdl");
        Object[] objects = client.invoke("getUser", 10002L);
        //输出调用结果
        System.out.println(objects[0].getClass());
        System.out.println(objects[0].toString());
    }

    /**
     * 动态调用
     * @throws Exception
     */
    public static void serviceTest2() throws Exception {

        JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
        // 记得要加入"?wsdl"
        Client client = factory.createClient("http://localhost:8080/soap/user?wsdl");
        // 指定到接口类所在包
        QName opName = new QName("http://api.ws.cans.com/", "getUser");
        Object[] res = client.invoke(opName, 10002L);
        System.out.println("Say: " + res[0]);
    }


}
